package com.msblearn.C_013;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CountDownLatch;

/**
 * HashMap对应得是TreeMap:TreeMap是使用红黑树实现的。TreeMap已经是排好序了的
 *
 */
public class T001_ConcurrentHashMap {
    public static void main(String[] args) throws InterruptedException {
        Map<String, String> map = new ConcurrentHashMap<>();
        ///高并发并且排序.没有ConcurrentTreeMap.使用CAS去实现ConcurrentTreeMap太过复杂
        //因此才有ConCurrentSkipListMap;
//        Map<String, String> map  =  new ConcurrentSkipListMap<>();

//        Map<String, String> map = new HashMap<>();
//        Map<String, String> map  = new Hashtable<>();
        Random r = new Random();
        Thread[] td = new Thread[100];
        CountDownLatch latch = new CountDownLatch(td.length);
        long start = System.currentTimeMillis();
        for (int i = 0; i < td.length; i++) {
            td[i] = new Thread(() -> {
                for (int j = 0; j < 10000; j++) {
                    map.put("a" + r.nextInt(100000), "a" + r.nextInt(100000));
                    latch.countDown();
                }
            });
        }

        Arrays.asList(td).forEach(t -> t.start());
        latch.await();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println(map.size());
    }
}
